package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.ConsumerMapper;
import com.goods.business.service.ConsumerService;
import com.goods.common.model.business.Consumer;
import com.goods.common.vo.business.ConsumerVO;
import com.goods.common.vo.system.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private ConsumerMapper consumerMapper;

    //物资去处分页列表展示
    @Override
    public PageVO<ConsumerVO> findConsumerList(Integer pageNum, Integer pageSize, String name, String address, String contact) {
        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(Consumer.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(name)){
            criteria.andLike("name","%" + name + "%");
        }
        if (!StringUtils.isEmpty(address)){
            criteria.andLike("address","%" + address + "%");
        }
        if (!StringUtils.isEmpty(contact)){
            criteria.andLike("contact","%" + contact + "%");
        }
        List<Consumer> consumerList = consumerMapper.selectByExample(example);
        List<ConsumerVO> consumerVOList = consumerList.stream().map(consumer -> {
            ConsumerVO consumerVO = new ConsumerVO();
            BeanUtils.copyProperties(consumer, consumerVO);
            return consumerVO;
        }).sorted(Comparator.comparingInt(ConsumerVO::getSort)).collect(Collectors.toList());
        PageInfo<Consumer> pageInfo = new PageInfo(consumerList);
        return new PageVO<>(pageInfo.getTotal(),consumerVOList);
    }

    //添加物资去处
    @Override
    public void addConsumer(Consumer consumer) {
        Calendar calendar = Calendar.getInstance();
        consumer.setCreateTime(calendar.getTime());
        consumer.setModifiedTime(calendar.getTime());
        consumerMapper.insertSelective(consumer);
    }

    //编辑物资去处
    @Override
    public Consumer editConsumer(Long id) {
        Consumer consumer = consumerMapper.selectByPrimaryKey(id);
        return consumer;
    }

    //更新物资去处
    @Override
    public void updateConsumer(Consumer consumer) {
        consumer.setModifiedTime(new Date());
        consumerMapper.updateByPrimaryKeySelective(consumer);
    }

    //删除物资去处
    @Override
    public void deleteConsumer(Long id) {
        consumerMapper.deleteByPrimaryKey(id);
    }

    //查询所有物资去处
    @Override
    public List<Consumer> findAllConsumer() {
        return consumerMapper.selectAll();
    }
}
